import {login, logout, UserList} from '@/api/user'
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'
import router from '@/router/index'
import {defineStore} from 'pinia'
import {ref, watch} from 'vue'
import {ElLoading, ElMessage} from 'element-plus'

const publicKey = 'MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANL378k3RiZHWx5AfJqdH9xRNBmD9wGD\n' + '2iRe41HdTNF8RUhNnHit5NpMNtGL0NPTSSpPjjI1kJfVorRvaQerUgkCAwEAAQ=='


export function encrypt(txt) {

    const encryptor = new JSEncrypt()

    encryptor.setPublicKey(publicKey) // 设置公钥

    return encryptor.encrypt(txt) // 对需要加密的数据进行加密

}

// import md5 from 'md5'
export const useUserStore = defineStore('user', () => {
    const loading = ref(false)

    const userInfo = ref({
        uuid: '', Name: '', headerImg: '', authority: {},
    })

    const token = ref(window.localStorage.getItem('token') || '')
    const setUserInfo = (val) => {
        userInfo.value = val
    }

    const setToken = (val) => {
        token.value = val
    }

    const NeedInit = () => {
        token.value = ''
        window.localStorage.removeItem('token')
        localStorage.clear()
    }

    const ResetUserInfo = (value = {}) => {
        userInfo.value = {
            ...userInfo.value, ...value
        }
    }

    const GetUserInfo = (value = {}) => {
        return sessionStorage.getItem('user');
    }

    /* 登录*/
    const LoginIn = async (loginInfo) => {
        loading.value = ElLoading.service({
            fullscreen: true, text: '登陆中，请稍候...',
        })

        userInfo.Name = loginInfo.username
        sessionStorage.setItem('user', loginInfo.username);

        userInfo.password = encrypt(loginInfo.password)

        const res = await login(loginInfo)
        if (res.status === 200) {
            loading.value.close()
            setUserInfo(res.data.user)
            setToken(res.data.token)
            ElMessage({
                type: 'success', message: '登录成功'
            })
            router.push({name: "dashboard"})
            return true
        } else {
            loading.value.close()
            ElMessage({
                type: 'fail', message: res.data.msg,
            })
            token.value = ''
            router.push({name: "login"})
        }
        loading.value.close()
        return false
    }

    /* 登出*/
    const LoginOut = async () => {
        const res = await logout()
        if (res.status === 200) {
            token.value = ''
            sessionStorage.clear()
            localStorage.clear()
            router.push({name: "Login"})
        }
    }

    //获取用户
    const GetUser = async () => {
        const res = await UserList()
        if (res.status === 200) {
            return res.data
        }
    }

    watch(token, () => {
        window.localStorage.setItem('token', token.value)
    })

    return {
        userInfo, token, NeedInit, ResetUserInfo, LoginIn, LoginOut, setToken, GetUser, GetUserInfo
    }
})
